package com.blue.encryption;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * @Description:  MAC（Message Authentication Code）消息认证码,单密钥的摘要算法
 *     参考资料https://blog.csdn.net/mn960mn/article/details/78174234
 *    其中，Mac.getInstance支持的算法有：HmacMD5、HmacSHA1、HmacSHA256等等
 * 	  全部支持的算法见官方文档：
 * 	  Security.getAlgorithms方法的使用详见API
 * 	  Security.getAlgorithms("Mac").forEach(System.out::println);
 * 	  https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Mac
 * @Auther: lbb
 * @Date: 2019/1/23 10:19
 */
public class MACUtil {
    /**
     * @param algorithm 算法
     * @param keyStr
     * @param bytes
     * @return
     */
    private static String macDigest(String algorithm, String keyStr,byte[] bytes){
        String macStr="";
        try {
            Mac mac=Mac.getInstance(algorithm);
            Key key = new SecretKeySpec(keyStr.getBytes(), "");
            mac.init(key);
            byte[] macdigest=mac.doFinal(bytes);
            macStr= Hex.encodeHexString(macdigest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return macStr;
    }

    /**
     * 获取HmacMD5
     * @param keyStr
     * @param content
     * @return
     */
    public static String getHmacMD5(String keyStr,String content){
        String hmacMD5Str="";
        try {
            hmacMD5Str=macDigest("HmacMD5",keyStr,content.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hmacMD5Str;
    }

    /**
     * 获取HmacSHA1
     * @param keyStr
     * @param content
     * @return
     */
    public static String getHmacSHA1(String keyStr,String content){
        String hmacSHA1Str="";
        try {
            hmacSHA1Str=macDigest("HmacSHA1",keyStr,content.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hmacSHA1Str;
    }
}
